package com.ktkj.init.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktkj.init.dto.RoleInfoCondition;
import com.ktkj.init.dto.RoleInfoForm;
import com.ktkj.init.entity.RoleInfo;
import com.ktkj.init.entity.RolePermissionMapping;
import com.ktkj.init.exception.BusinessException;
import com.ktkj.init.mapper.RoleInfoMapper;
import com.ktkj.init.service.RoleInfoService;
import com.ktkj.init.service.RolePermissionMappingService;
import com.ktkj.init.service.UserInfoService;
import com.ktkj.init.utils.SpringUtils;
import com.ktkj.init.vo.QueryResult;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author ktkj
 * @since 2021-12-31
 */
@Service
public class RoleInfoServiceImpl extends ServiceImpl<RoleInfoMapper, RoleInfo> implements RoleInfoService {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private RolePermissionMappingService rolePermissionMappingService;

    @Override
    public QueryResult<RoleInfo> page(RoleInfoCondition condition) {
        QueryWrapper<RoleInfo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(condition.getRoleCode())) {
            wrapper.eq("role_code", condition.getRoleCode().trim());
        }
        if (StringUtils.isNotBlank(condition.getRoleName())) {
            wrapper.like("role_name", condition.getRoleName().trim());
        }
        wrapper.orderByDesc("create_date");

        List<RoleInfo> resultData;
        long totalRecord;
        if (condition.getCurrent() != -1) {
            IPage<RoleInfo> page = page(new Page<>(condition.getCurrent(), condition.getPageSize()), wrapper);
            resultData = page.getRecords();
            totalRecord = page.getTotal();
        } else {
            resultData = list(wrapper);
            totalRecord = resultData.size();
        }
        QueryResult<RoleInfo> queryResult = new QueryResult<>();
        queryResult.setResultData(resultData);
        queryResult.setTotalRecord(totalRecord);
        return queryResult;
    }

    @Override
    @Transactional
    public RoleInfo saveOrUpdate(RoleInfoForm form) {
        RoleInfo bean = null;
        String errorMsg = "保存失败，请联系管理员！";
        try {
            Long userId = userInfoService.getByUserId();
            RoleInfo newRoleInfo = this.getByRoleCode(form.getRoleCode().trim());
            if (form.getId() != null) {
                bean = getById(form.getId());
                if (bean == null) {
                    errorMsg = "id错误，没有查询到对应数据！";
                    throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, errorMsg);
                }
                if (newRoleInfo != null && !newRoleInfo.getRoleCode().equals(bean.getRoleCode())) {
                    errorMsg = "角色编号不能重复！";
                    throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, errorMsg);
                }
                bean.setUpdateId(userId);
                bean.setUpdateDate(new Date());
            } else {
                if (newRoleInfo != null) {
                    errorMsg = "角色编号不能重复！";
                    throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, errorMsg);
                }
                bean = new RoleInfo();
                bean.setCreateId(userId);
            }
            SpringUtils.copyPropertiesIgnoreNull(form, bean);
            saveOrUpdate(bean);

            //关联角色与权限
            if (StringUtils.isNotBlank(form.getPermissionInfoIds())) {
                //先删除角色对应的权限
                QueryWrapper<RolePermissionMapping> wrapper = new QueryWrapper<>();
                wrapper.eq("role_id", bean.getId());
                rolePermissionMappingService.remove(wrapper);

                //再新增角色对应的权限
                List<Long> idList = Arrays.asList(form.getPermissionInfoIds().trim().split(",")).stream().map(
                        s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                List<RolePermissionMapping> rolePermissionMappingList = Lists.newArrayList();
                for (int i = 0; i < idList.size(); i++) {
                    RolePermissionMapping rolePermissionMapping = new RolePermissionMapping(bean.getId(), idList.get(i));
                    rolePermissionMappingList.add(rolePermissionMapping);
                }
                rolePermissionMappingService.saveBatch(rolePermissionMappingList, 10);
            }
        } catch (Exception e) {
            log.error(errorMsg, e);
            throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, errorMsg);
        }
        return bean;
    }


    public RoleInfo getByRoleCode(String roleCode) {
        RoleInfo bean = getOne(new QueryWrapper<RoleInfo>()
                .lambda()
                .eq(RoleInfo::getRoleCode, roleCode));
        return bean;
    }
}
